const app = getApp()

Page({
  data: {
    userInfo: {},
    carNumber: '',
    entryDate: '',
    entryTime: '',
    leaveDate: '',
    leaveTime: ''
  },

  onLoad() {
    // 检查登录状态
    if (!app.checkLogin()) return
    
    // 获取用户信息
    const userInfo = app.globalData.userInfo
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 设置默认时间
    const now = new Date()
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000)
    
    this.setData({
      userInfo,
      entryDate: this.formatDate(now),
      entryTime: this.formatTime(now),
      leaveDate: this.formatDate(tomorrow),
      leaveTime: this.formatTime(now)
    })
  },

  // 日期时间选择器事件处理
  onEntryDateChange(e) {
    this.setData({
      entryDate: e.detail.value
    })
  },

  onEntryTimeChange(e) {
    this.setData({
      entryTime: e.detail.value
    })
  },

  onLeaveDateChange(e) {
    this.setData({
      leaveDate: e.detail.value
    })
  },

  onLeaveTimeChange(e) {
    this.setData({
      leaveTime: e.detail.value
    })
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}-${this.padZero(month)}-${this.padZero(day)}`
  },

  // 格式化时间
  formatTime(date) {
    const hour = date.getHours()
    const minute = date.getMinutes()
    return `${this.padZero(hour)}:${this.padZero(minute)}`
  },

  // 补零
  padZero(num) {
    return num < 10 ? `0${num}` : num
  },

  // 提交申请
  async handleSubmit() {
    const { userInfo, carNumber, entryDate, entryTime, leaveDate, leaveTime } = this.data

    // 验证输入
    if (!carNumber) {
      wx.showToast({
        title: '请输入车牌号',
        icon: 'none'
      })
      return
    }

    // 验证时间
    const entryDateTime = new Date(`${entryDate} ${entryTime}`)
    const leaveDateTime = new Date(`${leaveDate} ${leaveTime}`)
    const now = new Date()

    if (entryDateTime < now) {
      wx.showToast({
        title: '进入时间不能早于当前时间',
        icon: 'none'
      })
      return
    }

    if (leaveDateTime <= entryDateTime) {
      wx.showToast({
        title: '离开时间必须晚于进入时间',
        icon: 'none'
      })
      return
    }

    try {
      const { result } = await wx.cloud.callFunction({
        name: 'submitApplication',
        data: {
          carNumber,
          entryTime: entryDateTime,
          expectedLeaveTime: leaveDateTime
        }
      })

      if (result.success) {
        wx.showToast({
          title: '申请提交成功',
          icon: 'success'
        })
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: result.message || '提交失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('提交申请失败', error)
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      })
    }
  }
}) 